package org.jeecg.modules.backstageModule.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.backstageModule.service.BackCustService;
import org.jeecg.modules.zonglzp.entity.User;
import org.jeecg.modules.zonglzp.service.CompanyService;
import org.jeecg.modules.zonglzp.util.WordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Random;

@RestController
@RequestMapping("/BackCust")
public class BackCustController {
    @Autowired
    private CompanyService companyservice;
    @Autowired
    BackCustService service;
    /*
    总后台我的客户查询
     */
    @GetMapping("/getBackCustList")
    public Result<?> getBackCustList(
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "status", defaultValue = "10") int status,
            String realName,
            String phone,
            String starttime,  //这两个时间用来计算这个区间内消费金额
            String endtime,
            String companyName,
            String companyCode
    ) {
        if(starttime!=null&&!"".equals(starttime))
           starttime=starttime.substring(1,10);
        else
            starttime=null;

        if(endtime!=null&&!"".equals(endtime))
            endtime=endtime.substring(1,10);
        else
            endtime=null;
        System.out.println(starttime+"输出看一看"+endtime);
        Page<User> page = new Page<User>(pageNo, pageSize);
        IPage<User> pageList = service.getBackCustList(page, realName, phone,starttime,endtime,companyName,companyCode,status);
        return Result.ok(pageList);
    }


    /*
     总后台查询用户详情
     */
    @GetMapping("/getBackCustDetail")
    public Result<?> getBackCustDetail(
            @RequestParam(name = "userId" ,defaultValue = "0") int userId
    ) {
        User user = service.getBackCustDetail(userId);
        if(user==null)
            return Result.ok(user);
        if(user.getIsMonth()==0){
          user.setIsMonthString("普通用户");
        }else{
            user.setIsMonthString("月结用户");
        }
        return Result.ok(user);
    }

    /*
    总后台中客户管理客户停用
    或者假删除  修改状态
     */
    @GetMapping("/stopCust")
    public Result<?> stopCust(
            int userId,
            int status
    ) {
        String msg = "";
        int count = service.stopCust(userId, status);
        if (count > 0) {
            msg = "成功";
        } else {
            msg = "失败";
        }
        return Result.ok(msg);
    }

    /*
   通过客户的ID编辑客户的信息
     */
    @PostMapping("/updateuser")
    public Result<?> updateuser(
            @RequestBody User user
    ) {
        //判断是否没有输入必要字段
        if (user.getUserName() == null || "".equals(user.getUserName())) {
            return Result.error("登录账号不能为空");
        }
//        if (user.getPassWord() == null || "".equals(user.getPassWord())) {
//            return Result.error("登录密码不能为空");
//        }
        //判断工号是否已经存在
//        String workname = companyservice.queryworknamebyworkname(user.getWorkNumber());
//        if (workname != null) {
//            return Result.error("该工号已存在!");
//        }
        //判断登录账号是否已经存在
//        String username = companyservice.queryusername(user.getUserName());
//        if (username != null) {
//            return Result.error("该账号已存在!");
//        }
       // User userInfo=service.getuserbyId(user.getId());
        //String passwordEncode = PasswordUtil.encrypt(userInfo.getWorkNumber(), user.getPassWord(), userInfo.getSalt());
        //设置密码
        //user.setPassWord(passwordEncode);
        //编辑用户信息
        int count = service.updateuser(user);
        return Result.ok();
    }

    /*
    设置月结
     */
    @GetMapping("/setUserMouth")
    public Result<?> setUserMouth(
            @RequestParam(name = "userId") int userId,
            @RequestParam(name = "isMonth",defaultValue = "0") int isMonth,
             String monthLines
    ) {
        if (monthLines == null || "".equals(monthLines)) {
            return Result.error("未填写月结额度，请填写");
        }

        int count = service.setUserMouth(userId, isMonth, monthLines);
        String msg = "";
        if (count > 0) {
            msg = "设置成功";
        } else {
            msg = "设置失败";
        }
        return Result.ok(msg);
    }

    /*
     总后台中客户管理新增客户
     */
    @PostMapping("/addBackCustomer")
    public Result<?> addBackCustomer(
            @RequestBody User user
    ) {
        HashMap<String,String> map;
        try {
            //判断是否没有输入必要字段
            if (user.getUserName() == null || "".equals(user.getUserName())) {
                return Result.error("登录账号不能为空");
            }


//            if (user.getPassWord() == null || "".equals(user.getPassWord())) {
//                return Result.error("登录密码不能为空");
//            }
            //判断工号是否已经存在
//        String workname = companyservice.queryworknamebyworkname(user.getWorkNumber());
//        if (workname != null) {
//            return Result.error("该工号已存在!");
//        }
            //判断登录账号是否已经存在
            String username = companyservice.queryusername(user.getUserName());
            if (username != null) {
                return Result.error("该账号已存在!");
            }


            //判断手机号是否已经存在是否已经存在
            String oldphone = companyservice.queryoldphone(user.getPhone());
            if (oldphone != null) {
                return Result.error("联系电话已经存在!");
            }

            if(user.getIsMonth()==1&&"".equals(user.getMonthLines())){
                return Result.error("未填写月结额度,请填写后再提交!");
            }
            if(user.getIsMonth()==0){
                user.setMonthLines("0");
                user.setRemainingLimit("0");
            }

            user.setRemainingLimit(user.getMonthLines());

            //先随机生成一个工号
            Long startTs = System.currentTimeMillis(); // 当前时间戳
            //8位随机数
            int random = new Random().nextInt(100) + 1;//为变量赋随机值1-99999999;
            String worknumber = random + (startTs.toString());
            user.setWorkNumber(worknumber);

            //设置密码眼
            String salt = oConvertUtils.randomGen(8);
            user.setSalt(salt);
          //  String passwordEncode = PasswordUtil.encrypt(worknumber, "123456", salt);
            String passwordEncode = PasswordUtil.encrypt(worknumber, String.valueOf(System.currentTimeMillis()), salt);
            //设置密码
            user.setPassWord(passwordEncode);
            user.setIdentity(2);
            //设置token
            String token = JwtUtil.sign(user.getUserName(), user.getPassWord());
            user.setToken(token);
            user.setCreateTime(new Date());

            //根据公司名字自动生成公司编号
            WordUtils util = new WordUtils();
            String wenzi = util.getUpperCase(user.getCompanyName(), false);
            user.setCompanyCode(wenzi+worknumber);
            int count = service.addBackCustomer(user);
            //通过账号查询这个user的id
            int userId = service.getuserIdbyusexrname(user.getUserName());
            user.setUserId(userId);

            //在userinfo表中插入用户之后 因为这个用户是公司，所以要继续插入进公司表中
            service.addusertoCompanyTable(user);

            //通过公司编号获取到刚才新增好的公司的id
            int companyId=service.getcompanyIdbycode(wenzi+worknumber);
            //给公司添加第一个默认的门店
            service.addfirststore(user.getCompanyName(),user.getCompanyCode()+"-1",user.getAddress(),new Date(),companyId,user.getPhone(),user.getRealName());

            //通过公司id得到刚才获取到的门店ID
            int storeId=service.getstoreIdbycompanyId(companyId);
            //将门店id赋给这个用户
            service.updateuserstoreId(userId,storeId);

            //赋值用户身份代码
            Long startTscode = System.currentTimeMillis(); // 当前时间戳
            //权限操作，加一个权限编码
            String newcode = "D"+startTscode;
            //权限操作，加一个权限编码
            service.updateOrgCode(userId, newcode);
            return Result.ok("增加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("增加失败");
        }
    }


}
